package com.hx.rpc;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Huathy
 * @date 2021-10-18 21:17
 * @description
 */
@Component
public class HxRpcServer implements ApplicationContextAware, InitializingBean {

    @SuppressWarnings("all")
    ExecutorService executorService = Executors.newCachedThreadPool();

    private int port;

    private Map<String, Object> handlerMap = new HashMap<>();

    public HxRpcServer(int port) {
        this.port = port;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            while (true){   //不断接收请求x
                Socket socket = serverSocket.accept();  //BIO
                //每一个socket，交给一个processor来处理
                executorService.execute(new ProcessorHandler(socket,handlerMap));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(serverSocket != null){
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(RpcService.class);
        if(!beanMap.isEmpty()){
            beanMap.values().forEach( serviceBean -> {
                //拿到注解
                RpcService rpcService = serviceBean.getClass().getAnnotation(RpcService.class);
                String serviceName = rpcService.value().getName();  //拿到接口类
                String version = rpcService.version();  //拿到版本号
                if(StringUtils.hasText(version)){
                    serviceName +=  "-" +version;
                }
                handlerMap.put(serviceName,serviceBean);
            } );
        }
    }
}
